package ServletCounter;

/**
 * @author 李某
 * * @date 2021/11/20
 * *物有本末，事有终始。知其先后者，则近道矣！
 * *荷花开满池塘的前一天还是半塘荷花半塘云。
 */


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

    /**
     * Servlet implementation class PageHitCounter
     */
    @WebServlet("/PageHitCounter")
    public class PageHitCounter extends HttpServlet {
        private static final long serialVersionUID = 1L;
        private int hitCount;

        @Override
        public void init()
        {
            // 重置点击计数器
            hitCount = 0;
        }

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            response.setContentType("text/html;charset=UTF-8");
            // 增加 hitCount
            hitCount++;
            PrintWriter out = response.getWriter();
            String title = "总点击量";
            String docType = "<!DOCTYPE html> \n";
            out.println(docType +
                    "<html>\n" +
                    "<head><title>" + title + "</title></head>\n" +
                    "<body bgcolor=\"#f0f0f0\">\n" +
                    "<h1 align=\"center\">" + title + "</h1>\n" +
                    "<h2 align=\"center\">" + hitCount + "</h2>\n" +
                    "</body></html>");
        }

        @Override
        public void destroy()
        {
            // 这一步是可选的，但是如果需要，您可以把 hitCount 的值写入到数据库
        }

    }

/**
 * 配套的XML
 * <?xml version="1.0" encoding="UTF-8"?>
 * <web-app>
 *   <servlet>
 *     <servlet-name>PageHitCounter</servlet-name>
 *     <servlet-class>com.runoob.test.PageHitCounter</servlet-class>
 *   </servlet>
 *   <servlet-mapping>
 *     <servlet-name>PageHitCounter</servlet-name>
 *     <url-pattern>/TomcatTest/PageHitCounter</url-pattern>
 *   </servlet-mapping>
 * </web-app>
 */

